package org.springframework.security.web.access.intercept;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher.MatchResult;
import org.springframework.security.web.util.matcher.RequestMatcherEntry;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author Dillon
 * @date 2024/7/28
 * @slogan 致敬大师 致敬未来的你
 * @desc 请求匹配代理授权管理器，用来执行请求管理器的不同实现
 */
public final class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> {

	private static final AuthorizationDecision DENY = new AuthorizationDecision(false);

	private final Log logger = LogFactory.getLog(getClass());

	private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings;

	private RequestMatcherDelegatingAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings) {
		Assert.notEmpty(mappings, "mappings cannot be empty");
		this.mappings = mappings;
	}

	/**
	 * 判断是否通过权限校验
	 *
	 * @param authentication 认证实现类
	 * @param request        访问资源
	 * @return 权限决策器
	 */
	@Override
	public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) {
		// 日志记录
		if (this.logger.isTraceEnabled()) {
			this.logger.trace(LogMessage.format("Authorizing %s", requestLine(request)));
		}
		// 循环所有注册的权限管理器
		for (RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings) {

			// 获取请求匹配器 只有请求匹配器匹配上，才执行权限认证
			RequestMatcher matcher = mapping.getRequestMatcher();
			MatchResult matchResult = matcher.matcher(request);
			if (matchResult.isMatch()) {
				AuthorizationManager<RequestAuthorizationContext> manager = mapping.getEntry();
				// 日志记录
				if (this.logger.isTraceEnabled()) {
					this.logger.trace(
							LogMessage.format("Checking authorization on %s using %s", requestLine(request), manager));
				}
				// 调用具体的授权管理器，校验权限
				return manager.check(authentication,
						new RequestAuthorizationContext(request, matchResult.getVariables()));
			}
		}
		// 日志记录
		if (this.logger.isTraceEnabled()) {
			this.logger.trace(LogMessage.of(() -> "Denying request since did not find matching RequestMatcher"));
		}
		// 默认鉴权不通过
		return DENY;
	}

	private static String requestLine(HttpServletRequest request) {
		return request.getMethod() + " " + UrlUtils.buildRequestUrl(request);
	}

	/**
	 * 返回 {@link RequestMatcherDelegatingAuthorizationManager}. 构建器
	 *
	 * @return RequestMatcherDelegatingAuthorizationManager
	 */
	public static Builder builder() {
		return new Builder();
	}

	/**
	 * 内部类
	 * 用于构建 {@link RequestMatcherDelegatingAuthorizationManager}.
	 */
	public static final class Builder {

		private boolean anyRequestConfigured;

		private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings = new ArrayList<>();

		/**
		 * 新增权限管理器与请求匹配器
		 *
		 * @param matcher 请求匹配器
		 * @param manager 权限权力其
		 * @return 权限管理器构建器
		 */
		public Builder add(RequestMatcher matcher, AuthorizationManager<RequestAuthorizationContext> manager) {
			Assert.state(!this.anyRequestConfigured, "Can't add mappings after anyRequest");
			Assert.notNull(matcher, "matcher cannot be null");
			Assert.notNull(manager, "manager cannot be null");
			this.mappings.add(new RequestMatcherEntry<>(matcher, manager));
			return this;
		}

		/**
		 * 消费者，用于自定义配置 权限管理器与请求匹配器 映射
		 *
		 * @param mappingsConsumer 消费者
		 * @return this
		 */
		public Builder mappings(
				Consumer<List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>>> mappingsConsumer) {
			Assert.state(!this.anyRequestConfigured, "Can't configure mappings after anyRequest");
			Assert.notNull(mappingsConsumer, "mappingsConsumer cannot be null");
			mappingsConsumer.accept(this.mappings);
			return this;
		}

		/**
		 * 配置所有请求拦截
		 *
		 * @return AuthorizedUrl
		 */
		public AuthorizedUrl anyRequest() {
			Assert.state(!this.anyRequestConfigured, "Can't configure anyRequest after itself");
			this.anyRequestConfigured = true;
			return new AuthorizedUrl(AnyRequestMatcher.INSTANCE);
		}

		/**
		 * 配置URL请求匹配器
		 *
		 * @param matchers 路径匹配器
		 * @return AuthorizedUrl
		 */
		public AuthorizedUrl requestMatchers(RequestMatcher... matchers) {
			Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest");
			return new AuthorizedUrl(matchers);
		}

		/**
		 * 构建 RequestMatcherDelegatingAuthorizationManager
		 *
		 * @return RequestMatcherDelegatingAuthorizationManager
		 */
		public RequestMatcherDelegatingAuthorizationManager build() {
			return new RequestMatcherDelegatingAuthorizationManager(this.mappings);
		}

		/**
		 * An object that allows configuring the {@link AuthorizationManager} for
		 * {@link RequestMatcher}s.
		 *
		 * @author Evgeniy Cheban
		 * @since 6.2
		 */
		public final class AuthorizedUrl {

			private final List<RequestMatcher> matchers;

			private AuthorizedUrl(RequestMatcher... matchers) {
				this(List.of(matchers));
			}

			private AuthorizedUrl(List<RequestMatcher> matchers) {
				this.matchers = matchers;
			}

			/**
			 * Specify that URLs are allowed by anyone.
			 *
			 * @return the {@link Builder} for further customizations
			 */
			public Builder permitAll() {
				return access((a, o) -> new AuthorizationDecision(true));
			}

			/**
			 * Specify that URLs are not allowed by anyone.
			 *
			 * @return the {@link Builder} for further customizations
			 */
			public Builder denyAll() {
				return access((a, o) -> new AuthorizationDecision(false));
			}

			/**
			 * Specify that URLs are allowed by any authenticated user.
			 *
			 * @return the {@link Builder} for further customizations
			 */
			public Builder authenticated() {
				return access(AuthenticatedAuthorizationManager.authenticated());
			}

			/**
			 * Specify that URLs are allowed by users who have authenticated and were not
			 * "remembered".
			 *
			 * @return the {@link Builder} for further customization
			 */
			public Builder fullyAuthenticated() {
				return access(AuthenticatedAuthorizationManager.fullyAuthenticated());
			}

			/**
			 * Specify that URLs are allowed by users that have been remembered.
			 *
			 * @return the {@link Builder} for further customization
			 */
			public Builder rememberMe() {
				return access(AuthenticatedAuthorizationManager.rememberMe());
			}

			/**
			 * Specify that URLs are allowed by anonymous users.
			 *
			 * @return the {@link Builder} for further customization
			 */
			public Builder anonymous() {
				return access(AuthenticatedAuthorizationManager.anonymous());
			}

			/**
			 * Specifies a user requires a role.
			 *
			 * @param role the role that should be required which is prepended with ROLE_
			 *             automatically (i.e. USER, ADMIN, etc). It should not start with ROLE_
			 * @return {@link Builder} for further customizations
			 */
			public Builder hasRole(String role) {
				return access(AuthorityAuthorizationManager.hasRole(role));
			}

			/**
			 * Specifies that a user requires one of many roles.
			 *
			 * @param roles the roles that the user should have at least one of (i.e.
			 *              ADMIN, USER, etc). Each role should not start with ROLE_ since it is
			 *              automatically prepended already
			 * @return the {@link Builder} for further customizations
			 */
			public Builder hasAnyRole(String... roles) {
				return access(AuthorityAuthorizationManager.hasAnyRole(roles));
			}

			/**
			 * Specifies a user requires an authority.
			 *
			 * @param authority the authority that should be required
			 * @return the {@link Builder} for further customizations
			 */
			public Builder hasAuthority(String authority) {
				return access(AuthorityAuthorizationManager.hasAuthority(authority));
			}

			/**
			 * 配置权限 任一权限即可
			 *
			 * @param authorities 权限数组
			 * @return this
			 */
			public Builder hasAnyAuthority(String... authorities) {
				return access(AuthorityAuthorizationManager.hasAnyAuthority(authorities));
			}

			/**
			 * 注册 授权管理器与 路径匹配器
			 *
			 * @param manager 授权管理器
			 * @return Builder
			 */
			private Builder access(AuthorizationManager<RequestAuthorizationContext> manager) {
				for (RequestMatcher matcher : this.matchers) {
					Builder.this.mappings.add(new RequestMatcherEntry<>(matcher, manager));
				}
				return Builder.this;
			}

		}

	}

}
